﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web.Mvc;
using CSF.Service.Accounts.Client;

namespace CSF.Utility.Mvc
{
    public class CsfAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            bool pass = true;

            var request = httpContext.Request;
            string path = request.Path;
            if (!string.IsNullOrEmpty(path) && request.IsAuthenticated)
            {
                string sessionId = request["SessionId"];
                string appCode = GetAppCode(httpContext);

                AuthorizeSvcClient svc = new AuthorizeSvcClient();
                pass = svc.CheckPermission(appCode, sessionId, path, request.QueryString.ToString(), request.Form.ToString());
                if (pass)
                {
                    pass = base.AuthorizeCore(httpContext);
                }
                return pass;
            }
            return base.AuthorizeCore(httpContext);
        }

        private string GetAppCode(System.Web.HttpContextBase httpContext)
        {
            string result = (string)httpContext.Cache["AppCode"];
            if (result == null)
            {
                var config = AccountServiceConfigManager.Load();
                result = config.AppCode;
                httpContext.Cache["AppCode"] = result;
            }
            return result;
        }
    }
}
